#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import aiortc
from aiortc.contrib.media import MediaRelay
import asyncio

# WebRTC URL解析
url = "webrtc://192.168.31.11/live/1ZNBHC900C009P-43-0-0"
server_address = url.split("webrtc://")[1].split("/live")[0]
stream_id = url.split("/live/")[1]

# ROS节点初始化
rospy.init_node('webrtc_image_publisher')

# 创建CvBridge实例
bridge = CvBridge()

# 创建WebRTC连接
async def run():
    # 创建一个RTCPeerConnection实例
    pc = aiortc.RTCPeerConnection()  # 直接创建实例，不使用 await

    try:
        # 异步设置远端描述
        await pc.set_remote_description(await aiortc.RemoteDescription(sdp=sdp))

        # 添加一个视频轨道
        video_track = pc.addTransceiver('video')

        # 创建MediaRelay来转发视频
        relay = MediaRelay()
        relay.connect(video_track, aiortc.MediaStreamTrack())

        # 接收视频帧并转换为ROS图像消息
        while True:
            frame = await relay.video_frames.get()
            # ... 其他代码 ...

        # await pc.close()
    finally:
        # 确保在最后关闭连接
        if 'pc' in locals():
            await pc.close()  # 确保关闭连接也是异步等待的

# 运行异步WebRTC连接
loop = asyncio.get_event_loop()
loop.run_until_complete(run())

# 运行异步WebRTC连接
loop = asyncio.get_event_loop()
loop.run_until_complete(run())